//
//  LCWenHTMLViewController.m
//  JKFuYinProject
//
//  Created by admin on 2018/6/25.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LCWenHTMLViewController.h"
#import "LCSpeakButton.h"
#import "CommunicateBottomView.h"
#import "LCHomePingLunTableViewController.h"
#import "LCWenHTMLViewController+LCPingLun.h"

@interface LCWenHTMLViewController ()
<MNShareMoreViewDelegate>

@property (nonatomic,strong) LCSpeakButton *speakButton;

@property (nonatomic,strong) CommunicateBottomView *bottomView;

@end

@implementation LCWenHTMLViewController
- (void)loadView {
    [super loadView];
//    self.isShowToolBar = YES;
    self.scriptNameArr = @[@"GetUserCode",@"get_article_detail",@"comment_view"];
    self.link =
    [NSString stringWithFormat:@"%@/52",self.link];
    _manager = [YYKeyboardManager defaultManager];
    [_manager addObserver:self];
}
- (void)dealloc {
    NSLog(@"__func__dealloc = %s", __func__);
    if (self.PlayAudio > 0) {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_LCPlayer play];//继续播放
        });
    }
    [self.progressView removeFromSuperview];
    [[YYKeyboardManager defaultManager] removeObserver:self];
    [self.webView clearHTMLCache];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"__func__dealloc = %s", __func__);
}

//- (CommunicateBottomView *)bottomView
//{
//    if (!_bottomView) {
//        _bottomView = [[CommunicateBottomView alloc]initWithFrame:CGRectZero CommunicateType:CommunicateBottomTypeDetailGray];
//    }
//    return _bottomView;
//}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self addkeyboardWillShow];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.progressView.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    #pragma mark -  评论条  -
//    [self.view addSubview:self.bottomView];
//    _bottomView.sd_layout.leftEqualToView(self.view).rightEqualToView(self.view)
//    .bottomEqualToView(self.view).heightIs(51);
    //底部评论条返回键交互
    @weakify(self)
    [[_bottomView.backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        @strongify(self)
        if ([self.webView canGoBack]) {
            [self.webView goBack];
            [self getjsTitle];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    [[_bottomView.communicateBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        @strongify(self)
        LCHomePingLunTableViewController *homePingLunTableViewController = [[LCHomePingLunTableViewController alloc] init];
        homePingLunTableViewController.id_id = self.model.id;
        homePingLunTableViewController.type = self.model.type;
        [self.navigationController pushViewController:homePingLunTableViewController animated:YES];
    }];
//    [[_bottomView.moreBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
//    }];
    [[_bottomView.praiseBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        NSLog(@"点赞");
        @strongify(self)
        [self.bottomView.praiseBtn popOutsideWithDuration:0.5];
        self.bottomView.is_like = YES;//!self.is_like;
        if(self.bottomView.is_like){
            [self.bottomView.praiseBtn setImage:self.bottomView.priaiseSelectedImage forState:UIControlStateNormal];
            [LSZRequestData UserVersusResourceThumbUp:self.model.id type:self.model.type :^(BOOL isOk, NSString * str, NSDictionary * dic) {
                if (isOk == YES) {
                }
                else{ //            [self setStringWarning:str];
                }
            }];
        }
        //        else{
        //            [self->_praiseBtn setImage:self->_priaiseImage forState:UIControlStateNormal];
        //        }
        [self.bottomView.praiseBtn animate];
    }];
    [[_bottomView.shareBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        @strongify(self)
        MNShareMoreView *moreView = [[MNShareMoreView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        moreView.delegate = self;
        [moreView appear];
    }];
    [_bottomView.viewBackColor tapGesture:^(UIGestureRecognizer *ges) {
//        @strongify(self)
        NSLog(@"编辑框");
    }];
    __weak typeof(self) weakSelf = self;
    self.shouldStartLoadBlock = ^(NSString *url) {
        NSLog(@"url = %@", url);
        @strongify(self)
        if ([url containsString:@"http://fuyin.app.inping.com/user/donation_article"]) {
            if([[_UserM usercode] isEqualToString:@""]){
                [self gotoLogin];
            }else{
                LCVideoHtmlDetailsController *viewController = [[LCVideoHtmlDetailsController alloc] init];
                viewController.link = url;
                [self.navigationController pushViewController:viewController animated:YES];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    viewController.title = @"赞赏支持";
                });
            }
            self.isLoad = NO;
        }
        if ([url containsString:@"http://buy.9ku.com/"]) {
            if([[_UserM usercode] isEqualToString:@""]){
                [weakSelf gotoLogin];
            }else{
                LSZFindOutMoreVC *viewController = [[LSZFindOutMoreVC alloc] init];
                viewController.type = @"2";
                viewController.link = url;
                [weakSelf.navigationController pushViewController:viewController animated:YES];
            }
            weakSelf.isLoad = NO;
        }else{
            weakSelf.isLoad = YES;
        }
    };
    
    self.customToolBar.itemClickBlock = ^(NSInteger itemTag){
        [weakSelf toolBarItemClickWithTag:itemTag];
    };
    
    [self setupRightBarButtonItem];
    
    [LCUtils setupLoginPromptWithAddSubview:self.view login:^(UILabel *loginLabel, UIView *loginView) {
        [loginLabel tapGesture:^(UIGestureRecognizer *ges) {
            @strongify(self)
            pushAccLoginVC;
        }];
        if(![[_UserM usercode] isEqualToString:@""]){
            loginView.hidden = YES;
        }
    }];
    [self initWithAppraise:self.view share:1];
}
- (void)setupWebViewLayout
{
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        if (@available(iOS 11, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-50);
        }else{
            make.top.equalTo(self.view.mas_top);
            make.bottom.equalTo(self.view.mas_bottom).offset(-50);
        }
    }];
    
}
- (void)setupWebViewCompatibilityADLayout
{
    CGFloat width = MIN(self.view.frame.size.width , self.view.frame.size.height);
    if([[_UserM usercode] isEqualToString:@""]){
        [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(self.view);
            if (@available(iOS 11, *)) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-50-50-width/20*3);
            }else{
                make.top.equalTo(self.view.mas_top);
                make.bottom.equalTo(self.view.mas_bottom).offset(-50-50-width/20*3);
            }
        }];
    }else{
        [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(self.view);
            if (@available(iOS 11, *)) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-50-width/20*3);
            }else{
                make.top.equalTo(self.view.mas_top);
                make.bottom.equalTo(self.view.mas_bottom).offset(-50-width/20*3);
            }
        }];
    }
}
- (void)setupRightBarButtonItem {
   self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"点点点"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
}
- (void)rightBtnClick
{
    @weakify(self)
    ACActionSheet *actionSheet = [[ACActionSheet alloc] initWithTitle:@"" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"不喜欢",@"意见反馈",@"诊断工具"] actionSheetBlock:^(NSInteger buttonIndex) {
        @strongify(self)
        //            NSLog(@"ACActionSheet block - %ld",buttonIndex);
        if (buttonIndex == 1) {
            SuggestMessageViewController * suggestVC = [[SuggestMessageViewController alloc] init];
            [self.navigationController pushViewController:suggestVC animated:YES];
        }
        if (buttonIndex == 2) {
            LCCheckToolViewController *viewController = [[LCCheckToolViewController alloc] init];
            viewController.playUrlPath = self.webView.URL.absoluteString;
            [self.navigationController pushViewController:viewController animated:YES];
        }

    }];
    [actionSheet show];
}
- (void)getjsTitle {
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"json"];
    [self.webView evaluateJavaScript:javascript completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        BeautifulEssayModel *detailModel = [BeautifulEssayModel yy_modelWithJSON:result];
        if (detailModel.title) {
            self.title = detailModel.title;
            self.model.title = detailModel.title;
            self.model.id = detailModel.id;
            self.model.type = detailModel.type;
            self.model.imageUrl = detailModel.thumb;
            self.model.discription = detailModel.discription;
            [self performSelector:@selector(loadIsDianZanData) withObject:nil afterDelay:0.00];//获取是否点赞
            self.model.commentNum = detailModel.commentNum;
//            _bottomView.pingLunNumLabel.text =
            _pingLunNumLabel.text =
            [NSString stringWithFormat:@"%@",self.model.commentNum];
        }
    }];
}
#pragma mark - MNShareMoreViewDelegate
-(void)MNShareMoreViewSelectedItem:(NSInteger)item
{
    if (item == 0) {
        [self shareBtnActionWithPlatformType:SSDKPlatformSubTypeWechatSession];
    }
    if (item == 1) {
        [self shareBtnActionWithPlatformType:SSDKPlatformSubTypeWechatTimeline];
    }
    if (item == 2) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSString *pasteboardString = [NSString stringWithFormat:@"%@", self.webView.URL.absoluteString];
        NSLog(@"点击复制链接后 复制%@",pasteboardString);
        pasteboard.string = pasteboardString;
        NSString *string =
        [NSString stringWithFormat:@"复制完毕"];
        [SVProgressHUD showSuccessWithStatus:string];
        [SVProgressHUD dismissWithDelay:1.3];
    }
}

/**
 *  工具条点击按钮的处理
 *
 *  @param tag 对应的item的tag值
 */
- (void)toolBarItemClickWithTag:(NSInteger)tag {
    switch (tag) {
        case 0: {
            if ([self.webView canGoBack]) {
                [self.webView goBack];
                [self getjsTitle];
            } else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
            break;
        case 1: {
            [self.webView goForward];
            [self getjsTitle];
        }
            break;
        case 2: {
            NSLog(@"这里分享按钮");
            //点击工具栏中的分享按钮
            [self shareBtnAction];
        }
            break;
        case 3: {
            [self.webView reloadFromOrigin];
        }
            break;
        case 4: {
            //DidClose
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
        default:
            break;
    }
}

- (void)shareBtnAction {
    NSArray *imageArray = @[[UIImage imageNamed:@"我的_设置_关于"]];
    if (imageArray) {
        NSString *link = self.webView.URL.absoluteString;
        if (link.length < 5) {
            if (self.webView.URL.absoluteString.length > 5) {
                link = self.webView.URL.absoluteString;
            }else{
                link = @"http://fuyin.app.inping.com/user/download";
            }
        }
        NSString *title = self.title;
        if (title.length == 0) {
            title = @"九酷福音";
        }
        if (self.model.discription.length < 1) {
            self.model.discription = @"九酷福音";
        }
        if ([title isEqualToString:@"加载中..."]) {
            return;
        }
        [self shareArticleAndImageArray:imageArray url:link title:title contentMessage:@"九酷福音" type:SSDKContentTypeWebPage tid:self.model.id];
    }
}
- (void)shareBtnActionWithPlatformType:(SSDKPlatformType)platformType {
    NSArray *imageArray = @[[UIImage imageNamed:@"我的_设置_关于"]];
    if (imageArray) {
        NSString *link = self.webView.URL.absoluteString;
        if (link.length < 5) {
            if (self.webView.URL.absoluteString.length > 5) {
                link = self.webView.URL.absoluteString;
            }else{
                link = @"http://fuyin.app.inping.com/user/download";
            }
        }
        NSString *title = self.title,*shareUrl = link;
        if (self.model) {
            shareUrl = self.model.shareUrl;
            title = self.model.title;
        }
        if (title.length == 0) {
            title = @"九酷福音";
        }
        if (self.model.discription.length < 1) {
            self.model.discription = @"九酷福音";
        }
        if ([title isEqualToString:@"加载中..."]) {
            return;
        }
//        [self shareShengJingMessageWithImageArray:imageArray url:link title:title contentMessage:@"九酷福音" type:SSDKContentTypeWebPage];
        [self shareNoUIWithImageArray:imageArray url:shareUrl title:title contentMessage:self.model.discription type:SSDKContentTypeWebPage platformType:(platformType)];
    }
}
/**
 *  正在加载
 */
- (void)webViewDidStartLoad {
    if ([self.title isEqualToString:self.model.title]) {
        return;
    }
    self.title = @"加载中...";
}
- (void)lcJavaScriptInteractionWithReceiveScriptMessage:(WKScriptMessage *)message {
    if([message.name isEqualToString:@"comment_view"]){
        
    }
    if([message.name isEqualToString:@"GetUserCode"]){
        [self performSelector:@selector(sendUserCode) withObject:nil afterDelay:1.0];
    }
    if([message.name isEqualToString:@"get_article_detail"]){
        //            NSLog(@"get_article_detail message.body = %@", message.body);
        BeautifulEssayModel *detailModel = [BeautifulEssayModel yy_modelWithJSON:message.body];
        if (detailModel.title) {
            self.title = detailModel.title;
            self.model.title = detailModel.title;
        }
//        if (detailModel.commentNum) {
//            self.pingLunNumLabel.text = detailModel.commentNum;
//            self.model.commentNum = detailModel.commentNum;
//            if ([detailModel.commentNum integerValue] > 99) {
//                [self.pingLunNumLabel sizeToFit];
//            }
//            //判断是否显示
//            if ([self.pingLunNumLabel.text isEqualToString:@"0"]) {
//                self.pingLunNumLabel.hidden = YES;
//            }else{
//                self.pingLunNumLabel.hidden = NO;
//            }
//        }
        if (detailModel.id && detailModel.type) {
            self.model.id = detailModel.id;
            self.model.type = detailModel.type;
            self.model.imageUrl = detailModel.thumb;
            self.model.discription = detailModel.discription;
            [self performSelector:@selector(getWen) withObject:nil afterDelay:1.0];
            [self performSelector:@selector(loadIsDianZanData) withObject:nil afterDelay:0.50];//获取是否点赞
            self.model.commentNum = detailModel.commentNum;
            self.pingLunNumLabel.text =
            [NSString stringWithFormat:@"%@",self.model.commentNum];
        }
    }
}
- (void)sendUserCode{
    NSArray *array = @[
                       @"login_ac('",
                       [_UserM usercode],
                       @"');",
                       ];
    NSString *JSString = [array componentsJoinedByString:@""];
    [self.webView evaluateJavaScript:JSString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    }];
}

/**
 *  获取当前加载的网页标题 , 弃用, 所以空实现
 */
- (void)getHtmlTitle:(NSString *)title {
    NSLog(@"class == %@  line == %d  func == %s", [self class], __LINE__, __FUNCTION__);
}

- (void)getHtmlContent:(NSString *)content {
//    NSLog(@"content = %@", content);
}
///获取Title
- (void)getWen {
    NSString *resource_id = self.model.id;
    NSString *type = self.model.type;
    NSString *urlStr = [NSString stringWithFormat:@"%@/article/article",http_zongSJUrl];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:resource_id, @"id",
                                type, @"type", nil];
    [kNetworkTool POSTFuYinWithUrlString:urlStr input:dictionary success:^(NSDictionary *dict) {
        NetWorkModel *netWorkModel = [NetWorkModel yy_modelWithJSON:dict];
        NSDictionary *dataDict = netWorkModel.data;
        NSString *title = dataDict[@"title"];
        if (title.length > 0) {
            weakSelf.title = title;
        }
        NSString *content = dataDict[@"content"];//content-article
        content = [NSString stringWithFormat:@"%@。 %@",weakSelf.title,content];
        content = [weakSelf getZZwithString:content];//去掉HTML标签
        if (content.length > 1) {
            [weakSelf.speakButton removeFromSuperview];
            LCSpeakButton *speakButton = [[LCSpeakButton alloc] initWithFrame:CGRectMake(ScreenWidth-50, NAVIGATION_BAR_HEIGHT - 64 + 110, 35, 35)];
            weakSelf.speakButton = speakButton;
//            speakButton.clickSpeak = ^{
//                [weakSelf unLiXianLoadbak];
//            };
//            if ([NSString stringWithFormat:@"%@",dataDict[@"title"]].length > 16) {
//                speakButton.frame = CGRectMake(ScreenWidth - 50, NAVIGATION_BAR_HEIGHT - 64 + 110 + 35, 35, 35);
//            }
            [speakButton roundV];
            speakButton.backgroundColor = [UIColor whiteColor];
            [weakSelf.view addSubview:speakButton];
            speakButton.strControl = content;
        }
        
    } failure:nil];

}
///正则去除网络标签
- (NSString *)getZZwithString:(NSString *)string {
    if (string.length < 1) {
        return @"";
    }
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n|&nbsp"
                            options:0
                              error:nil];
    string=[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
    return string;
}


- (void)loadIsDianZanData{
    NSString *resource_id = self.model.id;
    NSString *type = self.model.type;
    
    if ([_UserM.usercode isEqualToString:@""] || self.model.id == nil || self.model.type == nil) {
        return;
    }
    NetworkTool *networkTool = [NetworkTool sharedInstance];
    NSString *urlString = [NSString stringWithFormat:@"%@",http_shengjing];
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"is_fav", @"interface",
                                  resource_id, @"resource_id",
                                  type, @"type", nil];
    [networkTool POSTFuYinWithUrlString:urlString input:parameters success:^(NSDictionary *dict) {
        NetWorkModel *netWorkModel = [NetWorkModel yy_modelWithJSON:dict];
        if (netWorkModel.status == 1) {
//            self.bottomView.is_like = YES;
//            [self.bottomView.praiseBtn setImage:self.bottomView.priaiseSelectedImage forState:UIControlStateNormal];
            self.likeButtonSelected = YES;
            [self.likeButton setImage:[UIImage imageNamed:@"点赞_sel"] forState:UIControlStateNormal];
        }else{
            [self.likeButton setImage:[UIImage imageNamed:@"点赞"] forState:UIControlStateNormal];
        }
    } failure:^(NSError *error) {
        NSLog(@"error = %@", error);
    }];
}

- (BeautifulEssayModel *)model{
    if (_model == nil) {
        _model = [BeautifulEssayModel new];
    }
    return _model;
}

@end
